package smedi.ismedi.web.bff.infrastructure.util;


import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceInstance;
import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClient;
import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.NacosNamingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class NocosUtils {

    @Autowired
    private  NacosServiceDiscovery nacosServiceDiscovery;



    public ServiceInstance getServiceInstance(String serviceName) {
        List<Instance> allInstances = null;
        try {
            List<ServiceInstance> instances = nacosServiceDiscovery.getInstances(serviceName);

            for (ServiceInstance serviceInstance:  instances) {
                Boolean aBoolean =Boolean.parseBoolean (serviceInstance.getMetadata().get("nacos.healthy"));
                if( aBoolean){
                    return  serviceInstance;
                }
            }
            return  null;
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }



}
